﻿using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceModel;

namespace Sinacor.UI.HelpViewer.Service
{
    public class Receiver : IDisposable
    {
        #region Attributes

        private PipeService _ps = new PipeService();
        private bool _operational = false;
        private ServiceHost _host = null;
        private string _PipeName = string.Empty;
        
        #endregion

        #region Properties

        public PipeService.DocumentHelpReadyEventHandler DocumentHelpReady
        {
            get { return _ps.DocumentHelpReady; }
            set { _ps.DocumentHelpReady += value; }
        }

        public PipeService.LanguageChangedEventHandler LanguageChanged
        {
            get { return _ps.LanguageChanged; }
            set { _ps.LanguageChanged+= value; }
        }

        public PipeService.ThemeChangedEventHandler ThemeChanged
        {
            get { return _ps.ThemeChanged; }
            set { _ps.ThemeChanged += value; }
        }

        public Exception error = null;

        private const string DefaultPipeName = "Pipe";
        
        #endregion

        #region Constructors
        
        public Receiver() : this(DefaultPipeName)
        { 
        
        }
        
        public Receiver(string PipeName)
        {
            _PipeName = PipeName;
        }
        
        #endregion

        #region Public Methods

        public bool ServiceOn()
        {
            return (_operational = HostThisService());
        }

        public void ServiceOff()
        {
            if (_host != null)
                if (_host.State != CommunicationState.Closed)
                    _host.Close();

            _operational = false;
        }

        #endregion

        #region Private Methods
        
        private bool HostThisService()
        {
            try
            {
                _host = new ServiceHost(_ps, new Uri(PipeService.URI));
                _host.AddServiceEndpoint(typeof(IPipeService), new NetNamedPipeBinding(), _PipeName);
                _host.Open();

                _operational = true;
            }
            catch (Exception ex)
            {
                error = ex;
                _operational = false;
            }

            return _operational;
        }

        #endregion

        #region IDisposable Members

        public void Dispose()
        {
            this.ServiceOff();

            if (_ps != null)
                _ps = null;
        }

        #endregion
    }
}
